import type { Router } from 'vue-router';
import { startProgress, stopProgress } from '@vben/utils';
import { useAuthStore } from '#/store';
import { LOGIN_PATH } from '@vben/constants';

function setupCommonGuard(router: Router) {
  router.beforeEach((to) => {
    startProgress();

    const authStore = useAuthStore();

    // 定义登录相关的路径
    const loginPaths = ['/auth/login', '/auth/code-login', '/auth/qrcode-login', '/auth/register', '/auth/forget-password'];

    // 临时调试：确认路径信息和 token 状态
    console.log('Route Guard Debug:', {
      LOGIN_PATH,
      toPath: to.path,
      hasAccessToken: !!authStore.accessToken,
      hasValidToken: authStore.hasValidToken(),
      isLoginPath: loginPaths.includes(to.path) || to.path === LOGIN_PATH
    });

    // 如果访问的是登录相关页面，直接放行
    if (loginPaths.includes(to.path) || to.path === LOGIN_PATH) {
      console.log('Accessing login page, allowing access');
      return true;
    }

    // 使用 hasValidToken 方法检查 token 状态
    if (!authStore.hasValidToken()) {
      console.log('No valid token found, redirecting to login');
      return { path: LOGIN_PATH };
    }

    // 如果有有效的 token，允许访问
    console.log('Valid token found, allowing access');
    return true;
  });

  router.afterEach(() => {
    stopProgress();
  });
}

function createRouterGuard(router: Router) {
  setupCommonGuard(router);
}

export { createRouterGuard };
